<?php
class PostsController extends AppController {
	public $helpers = array (
			'Html',
			'Form',
			'Session' 
	);
	
	// function get text to show review on home page - ThanhLD1
	private function reviewText($maxLength, $html) {
		if (! $html)
			return "";
			// remove all tag html - ThanhLD1
		$result = trim ( strip_tags ( $html ) );
		if (empty ( $result )) {
			$result = "<p style=\"color: red;\">SORRY! NO REVIEW TEXT!</p>";
		}
		// cut string with length is maxLength - ThanhLD1
		if (strlen ( $result ) > $maxLength) {
			$result = substr ( $result, 0, $maxLength );
			$result .= "....";
		}
		
		return $result;
	}
	
	//action chuan bi data truoc khi chuyen qua action trang chu home
	public function index() {
		//delete cac session search truoc khi chuyen qua trang chu
		$this->Session->delete ( 'SearchCondition' );
		$this->Session->delete ( 'SearchTitle' );
		$this->Session->delete ( 'SearchUser' );
		$this->Session->delete ( 'SearchDateFrom' );
		$this->Session->delete ( 'SearchDateTo' );
		$this->Session->delete ( 'IsAdvanceSearch' );
		
		//chuyen sang action home
		return $this->redirect ( array (
				'controller' => 'posts',
				'action' => 'home' 
		) );
	}
	public function home() {
		// initiate number of data records on page - trieulh
		$this->Session->write ( 'limit', 5 );
		
		$this->loadModel ( 'Post' );
		// get num of page - ThanhLD1
		if (isset ( $_GET ['p'] ) && ( int ) ($_GET ['p'])) {
			$p = $_GET ['p'];
		} else {
			$p = 1;
		}
		
		// QuanNNM v
		
		//neu ton tai session search normal
		if ($this->Session->check ( 'SearchCondition' )) {
			//lay gia tri search normal condition
			$condition = $this->Session->read ( 'SearchCondition' );
			
			//select so dong du lieu tuong ung voi session search normal condition
			$numRow = $this->Post->find ( 'count', array (
					'conditions' => array (
							'Post.title LIKE' => '%' . $condition . '%' 
					),
					'order' => array (
							'Post.created DESC' 
					) 
			) );
			
			//neu so dong select duoc < 1
			if ($numRow < 1) {
				//set thong bao loi khong tim thay data
				$this->Session->setFlash ( 'No data found!', 'default', array (
						'class' => 'alert alert-danger' 
				) );
				
				//set bien $posts la mang 'Post' rong
				$this->loadModel ( 'Post' );
				$posts = $this->Post->create ();
			
			//neu so dong lay duoc >= 1
			} else {
				//set thong bao tim thay n dong du lieu
				$this->Session->setFlash ( 'Found ' . $numRow . ' results!', 'default', array (
						'class' => 'alert alert-success' 
				) );
				
				//select va set bien danh sach cac bai post $posts theo session search normal
				$posts = $this->Post->find ( 'all', array (
						'conditions' => array (
								'Post.title LIKE' => '%' . $condition . '%' 
						),
						'limit' => $p * 10,
						'order' => array (
								'Post.created DESC' 
						) 
				) );
			}
			
		//neu session danh dau dang thuc hien advance search la true
		} elseif ($this->Session->check ( 'IsAdvanceSearch' )) {
			//khai bao bien danh sach dieu kien search
			$listCondition = array ();
			
			//khai bao bien danh dau neu khong co du lieu search user theo dieu kien cua textbox search theo user post bai
			$isNodata = false;
			
			//neu session search theo user post bai duoc set
			if ($this->Session->check ( 'SearchUser' )) {
				//lay gia tri session
				$searchUser = $this->Session->read ( 'SearchUser' );
				
				//tim user co username giong nhu session dieu kien search
				$this->loadModel ( 'Admin' );
				$checkUser = $this->Admin->find ( 'first', array (
						'conditions' => array (
								'Admin.Username' => $searchUser 
						) 
				) );
				
				//neu khong tim thay user co username theo dieu kien search
				if (! $checkUser) {
					//set thong bao khong tim thay du lieu va set bien danh dau $isNodata = true
					$this->Session->setFlash ( 'No data found!', 'default', array (
							'class' => 'alert alert-danger' 
					) );
					$isNodata = true;
					
				//neu tim thay user co username theo dieu kien search
				} else {
					//set dieu kien search la user id do vao bien danh sach dieu kien
					array_push ( $listCondition, 'Post.Admin_id = ' . $checkUser ['Admin'] ['AdminID'] );
				}
			}
			
			//neu textbox search theo user post bai duoc input, nhung khong tim thay user nao thoa dieu kien search
			if ($isNodata) {
				//set thong bao khong tim thay du lieu
				$this->Session->setFlash ( 'No data found!', 'default', array (
						'class' => 'alert alert-danger' 
				) );
				
				//set bien $posts la mang 'Post' rong
				$this->loadModel ( 'Post' );
				$posts = $this->Post->create ();
			
			//neu textbox search theo user post bai duoc input, va tim thay user thoa dieu kien search
			} else {
				//neu ton tai session search theo title
				if ($this->Session->check ( 'SearchTitle' )) {
					//lay gia tri tu session nay va set vao danh sach dieu kien search
					$searchTitle = $this->Session->read ( 'SearchTitle' );
					array_push ( $listCondition, "Post.title LIKE '%" . $searchTitle . "%'" );
				}
				
				//neu ton tai session search theo date from
				if ($this->Session->check ( 'SearchDateFrom' )) {
					//lay gia tri tu session nay va set vao danh sach dieu kien search
					$searchDateFrom = $this->Session->read ( 'SearchDateFrom' );
					array_push ( $listCondition, "Post.created >= '" . $searchDateFrom . " 00:00:00'" );
				}
				
				//neu ton tai session search theo date to
				if ($this->Session->check ( 'SearchDateTo' )) {
					//lay gia tri tu session nay va set vao danh sach dieu kien search
					$searchDateTo = $this->Session->read ( 'SearchDateTo' );
					array_push ( $listCondition, "Post.created <= '" . $searchDateTo . " 23:59:59'" );
				}
				
				//select so dong du lieu ung voi danh sach dieu kien search
				$numRow = $this->Post->find ( 'count', array (
						'conditions' => $listCondition,
						'order' => array (
								'Post.created DESC' 
						) 
				) );
				
				//neu so dong du lieu < 1
				if ($numRow < 1) {
					//set thong bao loi khong tim thay du lieu
					$this->Session->setFlash ( 'No data found!', 'default', array (
							'class' => 'alert alert-danger' 
					) );
				
				//neu so dong du lieu >=1
				} else {
					//set thong bao tim thay n dong du lieu
					$this->Session->setFlash ( 'Found ' . $numRow . ' results!', 'default', array (
							'class' => 'alert alert-success' 
					) );
				}
				
				//select va set bien $posts, danh sach cac bai post thoa dieu kien search
				$posts = $this->Post->find ( 'all', array (
						'conditions' => $listCondition,
						'limit' => $p * 10,
						'order' => array (
								'Post.created DESC' 
						) 
				) );
			}
		
		//neu khong ton tai dieu kien search nao, xu ly get DB de lay danh sach tat ca bai post
		} else {
			$posts = $this->Post->find ( 'all', array (
					'conditions' => 'ORDER BY created DESC LIMIT ' . $p * 10 
			) );
		}
		// QuanNNM ^
		
		$editedPost = array ();
		
		// load data for sidebar hungdv7
		$sideBar_dateTime = array ();
		App::uses ( 'CakeTime', 'Utility' );
		$dummyStr = "";
		
		$this->loadModel ( 'Admin' );
		foreach ( $posts as $post ) {
			$textBody = $post ['Post'] ['body'];
			$bodyS = $this->reviewText ( 300, $textBody );
			$admin = $this->Admin->find ( 'first', array (
					'conditions' => array (
							'Admin.AdminID' => $post ['Post'] ['Admin_id'] 
					) 
			) );
			$post ['Post'] ['body'] = $bodyS;
			$post ['Post'] ['Username'] = $admin ['Admin'] ['Username'];
			array_push ( $editedPost, $post );
			
			// add data to $sideBar_dateTime array
			// cast date to string, get month_year only
			$rTime = CakeTime::format ( $post ['Post'] ['created'], '%B_%Y' );
			
			// check whether this month_year value is store in array, use temp string variable
			if (strpos ( $dummyStr, $rTime ) === false) {
				$dummyStr = $dummyStr . $rTime . ' ';
				array_push ( $sideBar_dateTime, array (
						'dateTime' => $rTime 
				) );
			}
		}
		
		// prepare data for render view of home
		$this->set ( 'dateTimeList', $sideBar_dateTime );
		$this->set ( 'posts', $editedPost );
		$this->set ( 'p', $p );
	}
	public function view($id = null) {
		if (! $id) {
			throw new NotFoundException ( __ ( 'Invalid post abc' ) );
		}
		// check the post with this id are exist or not. - ThanhLD1
		if (! $this->checkPost ( $id )) {
			$this->Session->setFlash ( 'This post not found or be deleted!', 'default', array (
					'class' => 'alert alert-danger' 
			) );
			$this->redirect ( '/posts/index' );
		}
		
		// get adminID if user logined
		$admin_id = 0;
		if ($this->Session->check ( "AdminLogin" )) {
			$admin = $this->Session->read ( "AdminLogin" );
			$admin_id = $admin ['Admin'] ['AdminID'];
		}
		
		// get the destination for back button
		$backDestination = $this->request->query ( 'b' );
		if ($this->request->query ( 'a' )) {
			$admin_id = $this->request->query ( 'a' );
		}
		// if backDestination is m then back button will transit to manage page, anything else transit to home page
		if (strcmp ( $backDestination, 'm' ) != 0) {
			$backDestination = '/posts/index';
		} else {
			$backDestination = '/admins/manage/' . $admin_id;
		}
		
		$post = $this->Post->findById ( $id );
		if (! $post) {
			throw new NotFoundException ( __ ( 'Invalid post' ) );
		}
		$this->loadModel ( 'Admin' );
		$admin = $this->Admin->find ( 'first', array (
				'conditions' => array (
						'Admin.AdminID' => $post ['Post'] ['Admin_id'] 
				) 
		) );
		// if the post doesn't belong to any admin, throw error
		if (! $admin) {
			throw new NotFoundException ( __ ( 'Invalid post' ) );
		}
		$post ['Post'] ['Username'] = $admin ['Admin'] ['Username'];
		
		
		//$this->set ( 'post', $post );
		
		// load comments belong to this post
		$this->loadModel ( 'Comment' );
		$listComment = $this->Comment->find ( 'all', array (
				'fields' => array (
						'Comment.content',
						'Comment.user',
						'Comment.created',
						'Comment.commentID' 
				),
				'conditions' => array (
						'Comment.post_ID' => $id 
				),
				'order' => array (
						'Comment.commentID DESC' 
				) 
		) );
		
		// split datetime variable to day, month, year variable - ThanhLD1
		list ( $y, $m, $dh ) = explode ( '-', $post ['Post'] ['created'] );
		list ( $d, $h ) = explode ( ' ', $dh );
		
		// set post data for redering view layout
		$this->set ( 'post', $post );
		$this->set ( 'm', $m );
		$this->set ( 'd', $d );
		$this->set ( 'numOfCom', sizeof ( $listComment ) );
		$this->set ( 'comments', $listComment );
		$this->set ( 'backDestination', $backDestination );		
	}
	public function add() {
		// check session logins hungdv7
		$this->Session->write ( 'authen', false );
		$logined = null;
		if ($this->Session->check ( 'AdminLogin' )) {
			$logined = $this->Session->read ( 'AdminLogin' );
		} else {
			
			$this->Session->setFlash ( 'Please login to access this function!', 'default', array (
					'class' => 'alert alert-danger' 
			) );
			// return to /post/index if check logined fail hungdv7
			return $this->redirect ( array (
					'controller' => 'posts',
					'action' => 'index' 
			) );
		}
		// save to db
		if ($this->request->is ( 'post' )) {
			$this->Post->create ();
			if ($this->Post->save ( $this->request->data )) {
				// search id for redirect to view.ctp
				$adminID = $this->Session->read ( 'AdminLogin' );
				$newPost = $this->Post->find ( 'first', array (
						'conditions' => array (
								'Post.Admin_id' => $adminID ['Admin'] ['AdminID'] 
						),
						'order' => 'Post.modified DESC' 
				) );
				$this->Session->setFlash ( 'Your post has been saved', 'default', array (
						'class' => 'alert alert-success' 
				) );
				
				return $this->redirect ( array (
						'controller' => 'posts',
						'action' => 'view',
						$newPost ['Post'] ['id'],
						'?' => array (
								'b' => 'm'//flag for backDestination 
						) 
				) );
			}
			$this->Session->setFlash ( 'Unable to save your post', 'default', array (
					'class' => 'alert alert-danger' 
			) );
		}
	}
	public function edit($id = null) {
		// check session logined hungdv7
		$this->Session->write ( 'authen', false );
		$logined = null;
		if ($this->Session->check ( 'AdminLogin' )) {
			$logined = $this->Session->read ( 'AdminLogin' );
		} else {
			$this->Session->setFlash ( 'Please login to access this function!', 'default', array (
					'class' => 'alert alert-danger' 
			) );
		// return to /post/index if check logined fail hungdv7
			return $this->redirect ( array (
					'controller' => 'posts',
					'action' => 'index' 
			) );
		}
		// check params
		if (! $id) {
			throw new NotFoundException ( __ ( 'Invalid post' ) );
		}
		
		$post = $this->Post->findById ( $id );
		if (! $post) {
			throw new NotFoundException ( __ ( 'Invalid post' ) );
		}
		// save to db
		if ($this->request->is ( 'post' ) || $this->request->is ( 'put' )) {
			if($post['Post']['Admin_id'] == $logined['Admin']['AdminID']) {
				$this->Post->id = $id;
				if ($this->Post->save ( $this->request->data )) {
					$this->Session->setFlash ( 'Your post has been updated', 'default', array (
							'class' => 'alert alert-success' 
					) );
					
					$this->set ( 'backDestination', '/admins/manage' );
					return $this->redirect ( array (
							'controller' => 'posts',
							'action' => 'view',
							$id,
							'?' => array (
									'b' => 'm' 
							) 
					) );
				}
			} else {
				$this->Session->setFlash ( 'Access denied!!!', 'default', array (
						'class' => 'alert alert-danger' 
				) );				
				return $this->redirect(array('action' => 'index'));
			}
			$this->Session->setFlash ( 'Unable to update your post', 'default', array (
					'class' => 'alert alert-danger' 
			) );
		}
		// initialize value if update date is not available
		if (! $this->request->data) {
			$this->request->data = $post;
		}
		// reder view layout for edit		
		$this->set ( 'post', $post );
	}
	public function delete($id) {
		// check session logined hungdv7 
		$this->Session->write ( 'authen', false );
		$logined = null;
		if ($this->Session->check ( 'AdminLogin' )) {
			$logined = $this->Session->read ( 'AdminLogin' );
		} else {			
			$this->Session->setFlash ( 'Please login to access this function!', 'default', array (
					'class' => 'alert alert-danger' 
			) );
			return $this->redirect ( array (
					'controller' => 'posts',
					'action' => 'index' 
			) );
		}
		
		// check request method, if not 'Post' throw error
		if ($this->request->is ( 'get' )) {
			throw new MethodNotAllowedException ();
		}
		
		// delete data in db, cascade setting help delete depedent child data
		if ($this->Post->delete ( $id )) {
			$this->Session->setFlash ( 'Deleted', 'default', array (
					'class' => 'alert alert-success' 
			) );
			return $this->redirect ( array (
					'controller' => 'admins',
					'action' => 'manage',
					$logined ['Admin'] ['AdminID'] 
			) );
		}
	}
	public function process() {
		$this->layout = "postLayout1";
		$this->loadModel ( 'Post' );
		// get position of list post to countinues loading - ThanhLD1
		if (isset ( $_POST ['start'] ) && ( int ) ($_POST ['start'])) {
			$start = $_POST ['start'];
		} else {
			$start = 10;
		}
		
		// QuanNNM v
		
		//neu ton tai session search normal
		if ($this->Session->check ( 'SearchCondition' )) {
			//lay gia tri sesison va set bien danh sach cac bai post $posts theo dieu kien session normal search
			$condition = $this->Session->read ( 'SearchCondition' );
			$posts = $this->Post->find ( 'all', array (
					'conditions' => array (
							'Post.title LIKE' => '%' . $condition . '%' 
					),
					'order' => array (
							'Post.created DESC' 
					),
					'offset' => $start,
					'limit' => 10 
			) );
		
		//neu session danh dau dang thuc hien advance search duoc set
		} elseif ($this->Session->check ( 'IsAdvanceSearch' )) {
			//khai bao bien danh sach dieu kien search
			$listCondition = array ();
			
			
			//check dieu kien search theo user post bai, neu da nhap tim kiem theo user post bai thi kiem tra user ton tai
			//neu user khong ton tai thi set bien $isNodata = true danh dau khong ton tai user
			$isNodata = false;
			if ($this->Session->check ( 'SearchUser' )) {
				$searchUser = $this->Session->read ( 'SearchUser' );
				$this->loadModel ( 'Admin' );
				$checkUser = $this->Admin->find ( 'first', array (
						'conditions' => array (
								'Admin.Username' => $searchUser 
						) 
				) );
				
				//new khong tim duoc user nhu dieu kien
				if (! $checkUser) {
					//set thong bao loi
					$this->Session->setFlash ( 'No data found!', 'default', array (
							'class' => 'alert alert-danger' 
					) );
					$isNodata = true;
				} else {
					//them vao danh sach dieu kien search la user id tim duoc
					array_push ( $listCondition, 'Post.Admin_id = ' . $checkUser ['Admin'] ['AdminID'] );
				}
			}
			
			//neu textbox search theo user post bai duoc input, nhung khong tim thay user nao thoa dieu kien search
			if ($isNodata) {
				//set bien $posts la mang 'Post' rong
				$this->loadModel ( 'Post' );
				$posts = $this->Post->create ();
				
			//neu textbox search theo user post bai duoc input, va tim thay user thoa dieu kien search
			} else {
				//kiem tra session dieu kien search theo title, neu ton tai add vao danh sach dieu kien search
				if ($this->Session->check ( 'SearchTitle' )) {
					$searchTitle = $this->Session->read ( 'SearchTitle' );
					array_push ( $listCondition, "Post.title LIKE '%" . $searchTitle . "%'" );
				}
				
				//kiem tra session dieu kien search theo date from, neu ton tai add vao danh sach dieu kien search
				if ($this->Session->check ( 'SearchDateFrom' )) {
					$searchDateFrom = $this->Session->read ( 'SearchDateFrom' );
					array_push ( $listCondition, "Post.created >= '" . $searchDateFrom . " 00:00:00'" );
				}
				
				//kiem tra session dieu kien search theo date to, neu ton tai add vao danh sach dieu kien search
				if ($this->Session->check ( 'SearchDateTo' )) {
					$searchDateTo = $this->Session->read ( 'SearchDateTo' );
					array_push ( $listCondition, "Post.created <= '" . $searchDateTo . " 23:59:59'" );
				}
				
				//select va set bien danh sach cac bai post $posts theo danh sach dieu kien search trong session
				$this->loadModel ( 'Post' );
				$posts = $this->Post->find ( 'all', array (
						'conditions' => $listCondition,
						'order' => array (
								'Post.created DESC' 
						),
						'offset' => $start,
						'limit' => 10 
				) );
			}
		
		//neu khong ton tai cac session search
		} else {
			$posts = $this->Post->find ( 'all', array (
					'conditions' => 'ORDER BY created DESC LIMIT ' . $start . ', 10' 
			) );
		}
		// QuanNNM ^
		
		$this->set ( 'posts', $posts );
	}	
	
	// function do previous post - ThanhLD1
	public function previousPost($id) {
		$newID = $id;
		$maxID = $this->getHighestPostID ();
		$minID = $this->getLowestPostID ();
		
		if ($newID == $minID) {
			// if this post is minium post id previous to post with max id
			$newID = $maxID;
		} else {
			// back to the post before
			$newID = $id - 1;
		}
		
		if ($this->checkPost ( $newID )) {
			// if the post before exist, redirect to that post detail
			$this->redirect ( "/posts/view/" . $newID );
		} else {
			// if the post before not exist, previous again the post before.
			$this->previousPost ( $newID );
		}
		
		$this->Session->setFlash ( 'Sorry! Something error!', 'default', array (
				'class' => 'alert alert-danger' 
		) );
	}
	
	// function do next post - ThanhLD1
	public function nextPost($id) {
		$newID = $id;
		$maxID = $this->getHighestPostID ();
		$minID = $this->getLowestPostID ();
		
		if ($newID == $maxID) {
			// if this post is max id, next to the post which have min id
			$newID = $minID;
		} else {
			// next to the post after
			$newID = $id + 1;
		}
		if ($this->checkPost ( $newID )) {
			// if the post after exist, redirect to that post detail
			$this->redirect ( "/posts/view/" . $newID );
		} else {
			// if the post after not exist, next again the post after.
			$this->nextPost ( $newID );
		}
		$this->Session->setFlash ( 'Sorry! Something error!', 'default', array (
				'class' => 'alert alert-danger' 
		) );
	}
	// function get highest post id in database -ThanhLD1 - edited by HungDV7
	public function getHighestPostID() {
		$this->loadModel ( 'Post' );
		$result = $this->Post->find ( 'first', array (
				'order' => array (
						'Post.id DESC' 
				) 
		) );
		
		if ($result) {
			$highest_id = $result ['Post'] ['id'];
			return $highest_id;
		} else
			return NULL;
	}
	
	// function get lowest post id in database -ThanhLD1 - edited by HungDV7
	public function getLowestPostID() {
		$this->loadModel ( 'Post' );
		$result = $this->Post->find ( 'first', array (
				'order' => array (
						'Post.id ASC' 
				) 
		) );
		
		if ($result) {
			$lowest_id = $result ['Post'] ['id'];
			return $lowest_id;
		} else
			return NULL;
	}
	
	// function check post is have data. - ThanhLD1
	public function checkPost($id) {
		$post = $this->Post->findById ( $id );
		if ($post) {
			return true;
		} else
			return false;
	}
}